package com.ruoyi.ftplet;

import org.apache.ftpserver.DataConnectionConfigurationFactory;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.util.HashMap;
import java.util.Map;

/**
 * 配置类
 */
@Configuration
public class FtpConfig extends CachingConfigurerSupport {


    @Value("${ftp.port}")
    private Integer ftpPort;


    @Value("${ftp.passivePorts}")
    private String ftpPassivePorts;

    @Value("${ftp.passiveExternalAddress}")
    private String ftpPassiveExternalAddress;




    @Bean
    public FtpServer createFtpServer(){
        FtpServerFactory serverFactory = new FtpServerFactory();

        ListenerFactory factory = new ListenerFactory();
        // 被动模式
        DataConnectionConfigurationFactory dataConnectionConfigurationFactory=new DataConnectionConfigurationFactory();
        dataConnectionConfigurationFactory.setIdleTime(600);
        dataConnectionConfigurationFactory.setActiveLocalPort(ftpPort);
        dataConnectionConfigurationFactory.setPassiveIpCheck(true);
        dataConnectionConfigurationFactory.setPassivePorts(ftpPassivePorts);
        dataConnectionConfigurationFactory.setPassiveExternalAddress(ftpPassiveExternalAddress);
        factory.setDataConnectionConfiguration(dataConnectionConfigurationFactory.createDataConnectionConfiguration());
        // replace the default listener
        serverFactory.addListener("default", factory.createListener());

        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        try
        {
            ClassPathResource classPathResource = new ClassPathResource("users.properties");
            userManagerFactory.setUrl(classPathResource.getURL());
        }
        catch (Exception e){
            throw new RuntimeException("配置文件users.properties不存在");
        }

        userManagerFactory.setPasswordEncryptor(new ClearTextPasswordEncryptor());
        serverFactory.setUserManager(userManagerFactory.createUserManager());

        Map<String, Ftplet> m = new HashMap<String, Ftplet>();
        m.put("miaFtplet", new UploadListener());

        serverFactory.setFtplets(m);
        // start the server
        FtpServer server = serverFactory.createServer();



        return server;
    }
}
